package com.ship.boats.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.boats.domain.CurrencyExchangeRate;
import com.ship.boats.domain.dto.*;
import com.ship.boats.domain.vo.ExportCurrencyExchangeRateInfo;
import com.ship.boats.domain.vo.QueryCurrencyConversionInfo;
import com.ship.boats.domain.vo.QueryCurrencyExchangeRateInfo;
import com.ship.boats.mapper.CurrencyExchangeRateMapper;
import com.ship.boats.service.CurrencyExchangeRateService;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Currency;
import java.util.Date;
import java.util.List;

/**
 * <b>CurrencyExchangeRateServiceImpl</b>
 *
 * @description: CurrencyExchangeRateServiceImpl <br>
 * @date: 2024/3/19 17:00 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class CurrencyExchangeRateServiceImpl implements CurrencyExchangeRateService {
    private static final Logger logger = LoggerFactory.getLogger(CurrencyExchangeRateServiceImpl.class);

    @Autowired
    private CurrencyExchangeRateMapper currencyExchangeRateMapper;


    @Override
    public boolean createCurrencyExchangeRate(CreateCurrencyExchangeRateRq rq) {
        CurrencyExchangeRate rate = new CurrencyExchangeRate();
        rate.setCurveDate(DateUtil.parse(rq.getCurveDate()+" 00:00:00",DatePattern.NORM_DATETIME_FORMATTER));
        rate.setCurrencyHeldType(rq.getCurrencyHeldType());
        rate.setCurrencyExchangeType(rq.getCurrencyExchangeType());
        rate.setExchangeRate(rq.getExchangeRate());
        rate.setOperatorDate(new Date());
        rate.setOperatorUser(SecurityUtils.getUsername());
        rate.setEnable("1");
        rate.setCreateUser(SecurityUtils.getUsername());
        rate.setCreateTime(new Date());
        rate.setUpdateUser(SecurityUtils.getUsername());
        rate.setUpdateTime(new Date());
        int insert = currencyExchangeRateMapper.insert(rate);
        if (insert == 1){
            return true;
        }
        return false;
    }

    @Override
    public QueryCurrencyExchangeRateInfo queryCurrencyExchangeRateById(String id) {
        QueryCurrencyExchangeRateInfo info = currencyExchangeRateMapper.queryCurrencyExchangeRateById(id);
        return info;
    }

    @Override
    public boolean updateCurrencyExchangeRateById(UpdateCurrencyExchangeRateRq rq) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",rq.getId());
        if (rq.getCurveDate() != null){
            updateWrapper.set("curve_date",DateUtil.parse(rq.getCurveDate()+" 00:00:00",DatePattern.NORM_DATETIME_FORMATTER));
        }
        if (StringUtils.isNotEmpty(rq.getCurrencyHeldType())){
            updateWrapper.set("currency_held_type",rq.getCurrencyHeldType());
        }
        if (StringUtils.isNotEmpty(rq.getCurrencyExchangeType())){
            updateWrapper.set("currency_exchange_type",rq.getCurrencyExchangeType());
        }
        updateWrapper.set("exchange_rate",rq.getExchangeRate());
        updateWrapper.set("operator_user",SecurityUtils.getUsername());
        updateWrapper.set("operator_date",new Date());
//        updateWrapper.set("update_user",SecurityUtils.getUsername());
        updateWrapper.set("update_time",new Date());
        int update = currencyExchangeRateMapper.update(null, updateWrapper);
        if (update == 1){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteCurrencyExchangeRateById(Long id) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("enable","0");
        updateWrapper.set("update_user",SecurityUtils.getUsername());
        updateWrapper.set("update_time",new Date());
        int update = currencyExchangeRateMapper.update(null, updateWrapper);
        if (update != 1){
            return false;
        }
        return true;
    }

    @Override
    public PageInfo<QueryCurrencyExchangeRateInfo> queryCurrencyExchangeRateList(QueryCurrencyExchangeRateRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<QueryCurrencyExchangeRateInfo> exchangeRateInfoList = currencyExchangeRateMapper.queryCurrencyExchangeRateList(rq);
        logger.info("查询币种汇率列表返回结果:{}"+ JSONUtil.parse(exchangeRateInfoList));
        PageInfo<QueryCurrencyExchangeRateInfo> pageInfo = new PageInfo<>(exchangeRateInfoList);
        return pageInfo;
    }

    @Override
    public List<ExportCurrencyExchangeRateInfo> exportCurrencyExchangeRateList(ExportCurrencyExchangeRateRq rq) {
        return currencyExchangeRateMapper.exportCurrencyExchangeRateList(rq);
    }

    @Override
    public boolean createCashForwardData(CurveDataRq curveData) {
        CurrencyExchangeRate currencyExchangeRate = new CurrencyExchangeRate();
        currencyExchangeRate.setCurveDate(DateUtil.parse(curveData.getCurveDate(), DatePattern.NORM_DATETIME_FORMATTER));
        if (StringUtils.isNotEmpty(curveData.getCurveName())){
            String[] split = curveData.getCurveName().split("-");
            currencyExchangeRate.setCurrencyHeldType(split[0]);
            currencyExchangeRate.setCurrencyExchangeType(split[1]);
        }
        currencyExchangeRate.setExchangeRate(curveData.getValue());
        currencyExchangeRate.setOperatorUser("期现一体化");
        currencyExchangeRate.setOperatorDate(new Date());
        currencyExchangeRate.setCurveUid(curveData.getCurveUID());
        currencyExchangeRate.setSettleFwd(curveData.getSettleFwd());
        currencyExchangeRate.setRangeSeq(curveData.getRangeSEQ());
        currencyExchangeRate.setRangeBegDate(DateUtil.parse(curveData.getRangeBegDate(), DatePattern.NORM_DATETIME_FORMATTER));
        currencyExchangeRate.setRangeEndDate(DateUtil.parse(curveData.getRangeEndDate(), DatePattern.NORM_DATETIME_FORMATTER));
        currencyExchangeRate.setEnable("1");
        currencyExchangeRate.setCreateUser("sys");
        currencyExchangeRate.setCreateTime(new Date());
        currencyExchangeRate.setUpdateUser("sys");
        //校验当前日期数据是否已存在
        String format = DateUtil.format(DateUtil.parse(curveData.getCurveDate(), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATE_FORMAT);
        CurrencyExchangeRate currencyExchangeRate1 = currencyExchangeRateMapper.queryCurrencyExchangeRateByName(curveData.getCurveName(),format);
        boolean status = false;
        if (currencyExchangeRate1 != null){
            currencyExchangeRate.setId(currencyExchangeRate1.getId());
            currencyExchangeRate.setOperatorDate(new Date());
            currencyExchangeRate.setUpdateTime(new Date());
            logger.info("修改期现一体化推送币种汇率数据参数:{}"+JSONUtil.parse(currencyExchangeRate));
            int i = currencyExchangeRateMapper.updateById(currencyExchangeRate);
            if (i == 1){
                status = true;
            }
        }else {
            currencyExchangeRate.setUpdateTime(new Date());
            logger.info("保存期现一体化推送币种汇率数据参数:{}"+JSONUtil.parse(currencyExchangeRate));
            int insert = currencyExchangeRateMapper.insert(currencyExchangeRate);
            if (insert == 1){
                status = true;
            }
        }
        return status;
    }

    @Override
    public QueryCurrencyConversionInfo queryCurrencyConversion(QueryCurrencyConversionRq rq) {
        QueryCurrencyConversionInfo info = new QueryCurrencyConversionInfo();
        CurrencyExchangeRate currencyExchangeRate = currencyExchangeRateMapper.queryCurrencyConversion(rq);
        if (null != currencyExchangeRate){
            Currency originalCurrency = Currency.getInstance(rq.getCurrencyHeldType()); // 原货币
            Currency targetCurrency = Currency.getInstance(rq.getCurrencyExchangeType()); // 目标货币
            if (rq.getCurrencyHeldNumber() != null){
                BigDecimal exchangeRate = new BigDecimal(currencyExchangeRate.getExchangeRate()); // 汇率
                BigDecimal convertedAmount = convertCurrency(rq.getCurrencyHeldNumber(), originalCurrency, targetCurrency, exchangeRate);
                info.setCurrencyExchangeNumber(convertedAmount);
                info.setCurrencyHeldNumber(rq.getCurrencyHeldNumber());
            }
            info.setCurrencyHeldType(rq.getCurrencyHeldType());
            info.setCurrencyExchangeType(rq.getCurrencyExchangeType());
            info.setDate(DateUtil.format(currencyExchangeRate.getCurveDate(),DatePattern.NORM_DATETIME_FORMATTER));
        }
        return info;
    }

    public static BigDecimal convertCurrency(BigDecimal originalAmount, Currency originalCurrency, Currency targetCurrency, BigDecimal exchangeRate) {
        // 获取两种货币的小数位数，以便进行正确的运算
        int originalScale = originalCurrency.getDefaultFractionDigits();
        int targetScale = targetCurrency.getDefaultFractionDigits();

        // 将金额转换为目标货币的汇率，保留正确的小数位数
        return originalAmount.multiply(exchangeRate.setScale(originalScale, BigDecimal.ROUND_HALF_UP))
                .setScale(targetScale, BigDecimal.ROUND_HALF_UP);
    }
}
